package com.mrslu.signkk.result;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.aliyun.core.utils.StringUtils;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serializable;
import java.util.List;

/**
 * @author 卢斌
 */
@Getter
@Setter
@NoArgsConstructor
public class Result<T> implements Serializable {

    Integer code;

    T data;

    String message = StringUtils.EMPTY;

    public static Result<?> ok() {
        Result<?> result = new Result<>();
        result.setCode(1);
        return jsonFilter(result);
    }


    public static <T>Result<T> ok(T data) {
        Result<T> result = new Result<>();
        result.setCode(1);
        result.setData(data);
        return jsonFilter(result);
    }


    public static Result<?> okList(List<?> data) {
        PageResult<?> pageResult = new PageResult<>(data);
        Result<PageResult<?>> result = new Result<>();
        result.setCode(1);
        result.setData(pageResult);
        return jsonFilter(result);
    }


    public static Result<?> fail(String msg) {
        Result<String> result = new Result<>();
        result.setCode(0);
        result.setMessage(msg);
        result.setData(StringUtils.EMPTY);
        return jsonFilter(result);
    }


    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }


    /**
     * JSON中包含大量值为空的字段，先通过fastJSON转化然后再转成Result对象可以处理掉空值字段。
     *
     * @param data  源数据
     * @param <T>   泛型
     * @return  空值过滤数据
     */
    private static <T>Result<T> jsonFilter(Result<T> data) {
        String passerby = JSON.toJSONString(data);
        return JSON.parseObject(passerby, new TypeReference<Result<T>>() {});
    }


}